package dt.inlee.common.tools;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

public class SysFunc {
	//编码
	public static String encoding="UTF-8";
	
	
	public static final int MESSAGE_OK = 1;
	public static final int MESSAGE_ERROR = 2;
	public static final int MESSAGE_NOTICE = 3;
	public static final int MESSAGE_INFORMATION = 4;
	public static final int MESSAGE_SAVE_OK = 5;
	public static final int MESSAGE_SAVE_ERROR = 6;
	public static final int MESSAGE_FEELACK = 7;
	public static final int MESSAGE_SAVE_PRINT = 8;



	public static String MoneyToString(Double value)
	{
		DecimalFormat df=new DecimalFormat("0.00");
		return df.format(value);
	}
	
	public static Integer StringToInteger(Object value) {
		if (value == null || value.equals("")) {
			return null;
		}
		try
		{
		return Integer.parseInt(value.toString());
		}
		catch(Exception ex)
		{
			return null;
		}
	}



	public static Date StringToDate(String value) {
		if (value == null) {
			return null;
		}
		try {
			if (value.length() > 10) {
				return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value);
			} else if(value.length()> 8) {
				return new SimpleDateFormat("yyyy-MM-dd").parse(value);
			} else {
				return new SimpleDateFormat("yy-MM-dd").parse(value);
			}
			
		} catch (Exception ex) {
			return null;
		}
	}

	public static String StringToString(String value) {
		
		if (value != null && value .equals("")) {
			return null;
		}
		if(value!=null)
		{
			return value.trim();
		}
		return value;
	}

	public static int StringToInt(String value) {
		if (value != null && !value.trim().equals("")) {
			try {
				return Integer.parseInt(value);
			} catch (Exception ex) {
				return -1;
			}
		}
		return -1;
	}



	public static Double StringToDouble(Object value) {
		if (value != null && !value.toString().trim().equals("")) {
			try
			{
				return Double.parseDouble(value.toString());
			}
			catch(Exception ex)
			{
				return 0.0;
			}
		}
		return 0.0;
	}
	
	public static String  encodingConvert(String str) throws UnsupportedEncodingException{
		str=new String(str.getBytes("iso-8859-1"),"GBK");
		return str;
	}


	
	public static String GetFileExt(String filename) {
		return filename.substring(filename.lastIndexOf('.') + 1);
	}


	public static String GetSeletedItems(HttpServletRequest request,
			String param) {
		String[] checked = request.getParameterValues(param);
		return StringJoin(checked, ",");
	}

	public static String StringJoin(Object[] array, String sep) {
		if (array == null) {
			return null;
		}
		if (array.length == 0) {
			return "";
		}
		if (sep == null) {
			sep = "";
		}
		StringBuilder sb = new StringBuilder();
		for (Object tkey : array) {
			sb.append(tkey);
			sb.append(sep);
		}
		int len = sb.length();
		sb.delete(len - sep.length(), len);
		return sb.toString();
	}

	@SuppressWarnings("resource")
    public static String ReadFromFile(String filename) {
		StringBuffer content = new StringBuffer();
		try {
			FileReader read = new FileReader(filename);
			BufferedReader br = new BufferedReader(read);
			String line;
			while ((line = br.readLine()) != null) {
				content.append(line + "\n");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content.toString();
	}

	public static void ShowReport(HttpServletRequest request,
			List<String> titles, String[] width, List<Object[]> queryData) {
		
		request.setAttribute("queryData", queryData);

		StringBuffer HtmlTitle = new StringBuffer();
		for (int i = 0; i < titles.size(); i++) {
			HtmlTitle.append(String.format("<td width='%s'>&nbsp%s</td>", width[i], titles.get(i)));
		}
		request.setAttribute("HtmlTitle", HtmlTitle.toString());

		StringBuffer HtmlData = new StringBuffer();
		for (int i = 0; i < queryData.size(); i++) {
			Object[] objects = queryData.get(i);
			HtmlData.append("<tr style='HEIGHT: 22px;'>");
			for (int k = 0; k < objects.length; k++) {
				HtmlData.append(String.format("<td width='%s'>&nbsp%s</td>",width[k], objects[k]));
			}
			HtmlData.append("</tr>");
		}
		
		
		request.setAttribute("HtmlData", HtmlData.toString());
	}


	public static String ShowChart(HttpServletRequest request, List<Object[]> queryData, Integer xIndex, Integer yIndex, Integer[] vIndexs)
	{
		StringBuffer xml=new StringBuffer();
		//xml.append("<chart palette='2' caption='运营趋势图' xAxisName='日期' yAxisName='取值' showValues='2' decimals='0' formatNumberScale='0' useRoundEdges='1'>");
		xml.append("<chart  caption='运营趋势图' subcaption='' lineThickness='1' showValues='0' formatNumberScale='0' anchorRadius='2' divLineAlpha='20' divLineColor='CC3300' divLineIsDashed='1' showAlternateHGridColor='1' alternateHGridAlpha='5' alternateHGridColor='CC3300' shadowAlpha='40' labelStep='2' numvdivlines='5' chartRightMargin='35' bgColor='FFFFFF,CC3300' bgAngle='270' bgAlpha='10,10'>");
		List<String> xValues=new ArrayList<String>();
		List<Object> yValues=new ArrayList<Object>();
		for(int i=0; i< queryData.size(); i++)
		{
			Object[] rows=queryData.get(i);
			if(rows.length<xIndex || rows.length < yIndex)
			{
				break;
			}
			if(!xValues.contains(rows[xIndex]))
			{
				xValues.add(rows[xIndex].toString());
			}

			if(rows[yIndex]==null)
			{
				rows[yIndex]="null";
			}
			if(!yValues.contains(rows[yIndex]))
			{
				yValues.add(rows[yIndex]);
			}
		}
		
		Collections.sort(xValues); 
		
		xml.append("<categories>");
		for(int i=0; i< xValues.size(); i++)
		{
			xml.append(String.format("<category label='%s'/>", xValues.get(i)));
		}
		xml.append("</categories>");
		
		
		for(int v=0; v<vIndexs.length; v++)
		{
			for(int i=0; i < yValues.size(); i++)
			{
				xml.append(String.format("<dataset seriesName='%s' color='%s' anchorBorderColor='F1683C' anchorBgColor='F1683C'>", yValues.get(i), RandomColor()));
				for(int k=0; k< queryData.size(); k++)
				{
					Object[] rows=queryData.get(k);
					if(rows[yIndex]!=null && rows[yIndex].equals(yValues.get(i)))
					{
						xml.append(String.format("<set value='%s'/>", rows[vIndexs[v]]));
					}									
						
				}
				xml.append("</dataset>");
			}
		}
		xml.append("<styles><definition><style name='CaptionFont' type='font' size='12' /></definition><application><apply toObject='CAPTION' styles='CaptionFont' /><apply toObject='SUBCAPTION' styles='CaptionFont' /></application></styles>");
		xml.append("</chart>");
		
		request.setAttribute("strXML", xml.toString());
		
		return xml.toString();
	}
	
	/************
	public static double sumBySql(String sql) {
		return ReportAction.sumBySql(sql);
	}

	public static int countBySql(String sql) {
		return ReportAction.countBySql(sql);
	}

	public static void queryBySql(String sql, List<String> titles,
			List<Object[]> queryData) {
		ReportAction.queryBySql(sql, titles, queryData);
	}

	public static boolean execBySql(String sql) {
		return ReportAction.execBySql(sql);
	}
	******************************************/
	public static String RandomString(int length) {
		StringBuffer buffer = new StringBuffer(
				"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
		StringBuffer sb = new StringBuffer();
		Random r = new Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			sb.append(buffer.charAt(r.nextInt(range)));
		}
		return sb.toString();
	}
	public static String RandomColor() {
		StringBuffer buffer = new StringBuffer(
				"0123456789ABCDEF");
		StringBuffer sb = new StringBuffer();
		Random r = new Random();
		int range = buffer.length();
		for (int i = 0; i < 6; i++) {
			sb.append(buffer.charAt(r.nextInt(range)));
		}
		return sb.toString();
	}
	public static String DownloadURL(String addr)
	{

		  URL url;
		  try {
		   url = new URL(addr);
		   InputStream ins = url.openStream();
		   BufferedReader bReader = new BufferedReader(new InputStreamReader(ins));
		   String line = bReader.readLine();
		   StringBuffer text=new StringBuffer();
		   while (line != null) {
			   byte[] bytes=line.getBytes();
			   text.append(new String(bytes, "GB2312"));
			   line = bReader.readLine();
		   }
		   return text.toString();
		  } catch (MalformedURLException e) {
		   System.out.println(e);
		  } catch (IOException e) {
		   System.out.println(e);
		  }
		  return "";
	}
}
